#include "Player.h"

#include "Engine.h"

#include "../Pieces/Pawn.h"
#include "../Pieces/Rook.h"
#include "../Pieces/Knight.h"
#include "../Pieces/Bishop.h"
#include "../Pieces/Queen.h"
#include "../Pieces/King.h"

namespace Core
{


	Player::Player(ChColor color, string name)
		: _color(color), _name(name)
	{
		int c1 = 0;
		_pieces[c1++] = new Rook(this, NULL);
		_pieces[c1++] = new Knight(this, NULL);
		_pieces[c1++] = new Bishop(this, NULL);
		_pieces[c1++] = new Queen(this, NULL);
		_pieces[c1++] = new King(this, NULL);
		_pieces[c1++] = new Bishop(this, NULL);
		_pieces[c1++] = new Knight(this, NULL);
		_pieces[c1++] = new Rook(this, NULL);

		for (int i = 0; i < 8; i++)
			_pieces[i+8] = new Pawn(this, NULL);
	}


	Player::~Player(void)
	{
		for (int i = 0; i < 16; i++)
			delete _pieces[i];

		for (int i = 0; i < _pieces2.size(); i++)
			delete _pieces2[i];
	}

	Piece * Player::getPiece(int i) const
	{
		if(i < 0 || i > 15)
			return NULL;
		return _pieces[i];
	}
		
	void Player::deleteValidMoves()
	{
		for (int i = 0; i < 16; i++)
			if(!_pieces[i]->isEaten())
				_pieces[i]->deleteValidMoves();

		for (int i = 0; i < _pieces2.size(); i++)
			if(!_pieces2[i]->isEaten())
				_pieces2[i]->deleteValidMoves();
	}

	vector<Piece*> & Player::promotes()
	{
		return _pieces2;
	}

	void Player::move(int r0, int c0, int r1, int c1)
	{
		Engine::instance()->move(r0, c0, r1, c1);
	}

	void Player::move()
	{
		Move * m = NULL;
		for (int i = 0; i < 16; i++)
			if(!_pieces[i]->isEaten() && _pieces[i]->validMoves().size() > 0)
			{
				m = _pieces[i]->validMoves().begin()->second;
				break;
			}
		if(m == NULL)
			for (int i = 0; i < _pieces2.size(); i++)
				if(!_pieces2[i]->isEaten() && _pieces2[i]->validMoves().size() > 0)
				{
					m = _pieces2[i]->validMoves().begin()->second;
					break;
				}
		if(m == NULL)
			throw "Player has no valid move!";
		Engine::instance()->move(m->from()->row(), m->from()->column(), m->to()->row(), m->to()->column());
	}


	bool Player::canMoveAny()
	{
		for (int i = 0; i < 16; i++)
			if(!_pieces[i]->isEaten() && _pieces[i]->validMoves().size() > 0)
				return true;

		for (int i = 0; i < _pieces2.size(); i++)
			if(!_pieces2[i]->isEaten() && _pieces2[i]->validMoves().size() > 0)
				return true;

		return false;
	}
}
